package com.gti.mobilsafe.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;

import android.app.ProgressDialog;

public class DownUtil {

	public static File download(String serverpath,String savepath,ProgressDialog pd){
		try {
			File file = new File(savepath);
			//URL url = new URL(serverpath);
			HttpClient client = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(serverpath);
			HttpResponse response = client.execute(httpGet);
			if(response.getStatusLine().getStatusCode()==200){
				int max = (int)response.getEntity().getContentLength();
				pd.setMax(max);
				InputStream is  = response.getEntity().getContent();
				FileOutputStream fos =  new FileOutputStream(file);
				byte[] buffer = new byte[1024];
				int len = 0;
				int total =0;
				
				while( (len = is.read(buffer))!=-1){
					fos.write(buffer, 0, len);
					total += len;
					pd.setProgress(total);
				}
				fos.flush();
				fos.close();
				
				return file;
			}
		} catch (Exception e) {
		
			e.printStackTrace();
		    return null;
		}
		return null;
		
	}
	
	public static String getFileName(String serverPath){
		return serverPath.substring(serverPath.lastIndexOf("/")+1);	
	}
}
